﻿// ***********************************************************************
// Assembly         : DonNicky.Common
// Author           : donnicky
// Created          : 11-26-2012
//
// Last Modified By : donnicky
// Last Modified On : 12-07-2012
// ***********************************************************************
using System.ComponentModel.DataAnnotations;
using System.IO;

namespace DonNicky.Common.Validation
{
    /// <summary>
    /// Checks if the specified file exists
    /// </summary>
    public class FileExistsAttribute : ValidationAttribute
    {
        /// <summary>
        /// Determines whether the specified file exists.
        /// </summary>
        /// <param name="value">The file path to validate.</param>
        /// <returns>true if the specified file path exists (or provided value is null or empty); otherwise, false.</returns>
        public
#if NET4
        override
#endif
 bool IsValid(object value)
        {
            return value == null || string.IsNullOrEmpty(value.ToString()) || File.Exists(value.ToString());
        }

        /// <summary>
        /// Determines whether the specified file exists.
        /// </summary>
        /// <param name="value">The file path to validate.</param>
        /// <param name="validationContext">The context information about the validation operation.</param>
        /// <returns>An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class.</returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            return IsValid(value) ? ValidationResult.Success : new ValidationResult(ErrorMessage);
        }
    }
}
